package com.promis.okhttp;

import android.os.Handler;
import android.os.Message;

import java.lang.ref.WeakReference;

/**
 * Created by jidanbo on 2018/1/31.
 */

public abstract class ProgressResponseListener {

    private static final int RESPONSE_UPDATE = 0x02;

    private final WeakReference<ProgressResponseListener> progressResponseListenerWeakReference;
    private Handler handler;

    public ProgressResponseListener() {
        progressResponseListenerWeakReference = new WeakReference<>(this);
        handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                switch (msg.what) {
                    case RESPONSE_UPDATE:
                        ProgressResponseListener uiProgressResponseListener = progressResponseListenerWeakReference.get();
                        if (uiProgressResponseListener != null) {
                            //获得进度实体类
                            ProgressModel progressModel = (ProgressModel) msg.obj;
                            //回调抽象方法
                            onResponseProgress(progressModel.getCurrentBytes(), progressModel.getContentLength(), progressModel.isDone());
                        }
                        break;
                    default:
                        super.handleMessage(msg);
                        break;
                }
            }
        };
    }

    void setResponseUpdate(long bytesRead, long contentLength, boolean done) {
        Message message = Message.obtain();
        message.obj = new ProgressModel(bytesRead, contentLength, done);
        message.what = RESPONSE_UPDATE;
        handler.sendMessage(message);
    }

    public abstract void onResponseProgress(long bytesRead, long contentLength, boolean done);
}
